/*
 * Copyright (c) 2018, Nordic Semiconductor
 * All rights reserved.
 * ...
 */

package no.nordicsemi.android.nrfmesh;

import android.annotation.SuppressLint;          // ★ for SDK_INT and MissingSuperCall
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationBarView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.splashscreen.SplashScreen;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.ViewModelProvider;
import dagger.hilt.android.AndroidEntryPoint;
import no.nordicsemi.android.nrfmesh.databinding.ActivityMainBinding;
import no.nordicsemi.android.nrfmesh.viewmodels.SharedViewModel;
import no.nordicsemi.android.nrfmesh.widgets.CustomControlsActivity;

@AndroidEntryPoint
public class MainActivity extends AppCompatActivity implements
        NavigationBarView.OnItemSelectedListener,
        NavigationBarView.OnItemReselectedListener {

    private static boolean coldStart = true;
    private static final String CURRENT_FRAGMENT = "CURRENT_FRAGMENT";

    private SharedViewModel mViewModel;

    private NetworkFragment mNetworkFragment;
    private GroupsFragment mGroupsFragment;
    private ProxyFilterFragment mProxyFilterFragment;
    private Fragment mSettingsFragment;

    // ▼ 滑动返回相关字段
    private GestureDetector gestureDetector;
    private static final int SWIPE_THRESHOLD = 100;
    private static final int SWIPE_VELOCITY_THRESHOLD = 100;
    private int edgeSlopPx;     // ★ 边缘判定宽度 (px)
    private int screenWidthPx;  // ★ 屏幕宽度 (px)

    @SuppressLint("ObsoleteSdkInt") // ★ suppress “SDK_INT always >= …” warnings
    @Override
    protected void onCreate(@Nullable final Bundle savedInstanceState) {
        setTheme(R.style.AppTheme);
        super.onCreate(savedInstanceState);

        mViewModel = new ViewModelProvider(this).get(SharedViewModel.class);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            final SplashScreen splashScreen = SplashScreen.installSplashScreen(this);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                if (coldStart) {
                    coldStart = false;
                    splashScreen.setKeepOnScreenCondition(() ->
                            mViewModel.getNetworkLiveData().getMeshNetwork() == null
                    );
                }
            }
        }

        final ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        setSupportActionBar(binding.toolbar);
        if (getSupportActionBar() != null)
            getSupportActionBar().setTitle(R.string.app_name);

        mNetworkFragment = (NetworkFragment) getSupportFragmentManager()
                .findFragmentById(R.id.fragment_network);
        mGroupsFragment = (GroupsFragment) getSupportFragmentManager()
                .findFragmentById(R.id.fragment_groups);
        mProxyFilterFragment = (ProxyFilterFragment) getSupportFragmentManager()
                .findFragmentById(R.id.fragment_proxy);
        mSettingsFragment = getSupportFragmentManager()
                .findFragmentById(R.id.fragment_settings);

        final BottomNavigationView bottomNavigationView =
                findViewById(R.id.bottom_navigation_view);
        bottomNavigationView.setOnItemSelectedListener(this);
        bottomNavigationView.setOnItemReselectedListener(this);

        if (savedInstanceState == null) {
            onNavigationItemSelected(bottomNavigationView
                    .getMenu().findItem(R.id.action_network));
        } else {
            bottomNavigationView
                    .setSelectedItemId(savedInstanceState.getInt(CURRENT_FRAGMENT));
        }

        // ▼ 初始化手势检测
        gestureDetector = new GestureDetector(this, new SwipeGestureListener());

        // ★ 计算左侧/右侧边缘触发宽度 (24dp)，并记录屏幕宽度 (px)
        DisplayMetrics dm = getResources().getDisplayMetrics();
        edgeSlopPx    = (int) (24 * dm.density);
        screenWidthPx = dm.widthPixels;
    }

    // ▼ 捕获所有触摸事件，识别滑动但不拦截
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (gestureDetector != null) {
            gestureDetector.onTouchEvent(ev);
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onCreateOptionsMenu(final Menu menu) {
        final Boolean isConnectedToNetwork = mViewModel.isConnectedToProxy().getValue();
        if (isConnectedToNetwork != null && isConnectedToNetwork) {
            getMenuInflater().inflate(R.menu.disconnect, menu);
        } else {
            getMenuInflater().inflate(R.menu.connect, menu);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(final MenuItem item) {
        final int id = item.getItemId();
        if (id == R.id.action_connect) {
            mViewModel.navigateToScannerActivity(this, false);
            return true;
        } else if (id == R.id.action_disconnect) {
            mViewModel.disconnect();
            return true;
        }
        return false;
    }

    @SuppressLint("MissingSuperCall")
    @Override
    public void onBackPressed() {
        navigateBackToCustom();
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        final int id = item.getItemId();
        final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        if (id == R.id.action_network) {
            ft.show(mNetworkFragment)
                    .hide(mGroupsFragment)
                    .hide(mProxyFilterFragment)
                    .hide(mSettingsFragment);
        } else if (id == R.id.action_groups) {
            ft.hide(mNetworkFragment)
                    .show(mGroupsFragment)
                    .hide(mProxyFilterFragment)
                    .hide(mSettingsFragment);
        } else if (id == R.id.action_proxy) {
            ft.hide(mNetworkFragment)
                    .hide(mGroupsFragment)
                    .show(mProxyFilterFragment)
                    .hide(mSettingsFragment);
        } else if (id == R.id.action_settings) {
            ft.hide(mNetworkFragment)
                    .hide(mGroupsFragment)
                    .hide(mProxyFilterFragment)
                    .show(mSettingsFragment);
        }
        ft.commit();
        invalidateOptionsMenu();
        return true;
    }

    @Override
    public void onNavigationItemReselected(@NonNull MenuItem item) {
        // No-op
    }

    // ▼ 内部类：处理左右边缘滑动
    private class SwipeGestureListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onDown(MotionEvent e) {
            // 必须返回 true，才能继续接收后续 onFling()
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2,
                               float velocityX, float velocityY) {
            if (e1 == null || e2 == null) return false;

            float startX = e1.getX();
            float diffX  = e2.getX() - startX;
            float diffY  = e2.getY() - e1.getY();

            // 左侧边缘 → 右滑
            if (startX <= edgeSlopPx
                    && Math.abs(diffX) > Math.abs(diffY)
                    && diffX > SWIPE_THRESHOLD
                    && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                navigateBackToCustom();
                return true;
            }
            // 右侧边缘 → 左滑
            if (startX >= screenWidthPx - edgeSlopPx
                    && Math.abs(diffX) > Math.abs(diffY)
                    && diffX < -SWIPE_THRESHOLD
                    && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                navigateBackToCustom();
                return true;
            }
            return false;
        }
    }

    @SuppressWarnings("deprecation")
    private void navigateBackToCustom() {
        finish();
        overridePendingTransition(
                android.R.anim.slide_in_left,
                android.R.anim.slide_out_right
        );
    }
}
